import {  Card ,Table,Tooltip,Upload,Modal, message } from 'antd';
import {
  PlusOutlined
} from '@ant-design/icons';
import { history } from 'umi';
import { connect} from 'umi';
import React, {useEffect} from 'react';
import { GridContent } from '@ant-design/pro-layout';
import { upload } from './service'
import {HasPermission} from '@/components/AuthComponent/HasPermission';
const AuthPlus = HasPermission(PlusOutlined);
const AuthUpload = HasPermission(Upload);

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

/**
 * 体测记录
 * @param {*} props 
 */
const columns = [
  {
    title: '体测时间',
    dataIndex: 'bodyExaminationTime',
  },
  {
    title: '身高/cm',
    dataIndex: 'height',
  },
  {
    title: '体重/kg',
    dataIndex: 'weight',
  },
  {
    title: '体脂率/%',
    dataIndex: 'bodyFatRate',
  },
  {
    title: '水分率/%',
    dataIndex: 'moistureDatio',
  },
  {
    title: '肌肉率/%',
    dataIndex: 'muscleRate',
  },
  {
    title: '体型判断',
    dataIndex: 'bodyShapeJudgment',
  },
  {
    title: '代谢年龄',
    dataIndex: 'metabolicAge',
  },
  {
    title: '骨含量/%',
    dataIndex: 'boneContent',
  },
  {
    title: '内脂含量/%',
    dataIndex: 'lactoneContent',
  },
  {
    title: '体测对比',
    dataIndex: 'somatometricComparison',
  },
];
const Info = props => {
  const { dispatch, id,bordyRecord,loading} = props
  const [previewVisible, setPreviewVisible] = React.useState(false);
  const [previewImage, setPreviewImage] = React.useState("");
  const [previewTitle, setPreviewTitle] = React.useState("");
  const [fileList, setFileList] = React.useState([]);
  const [imgLoading, setImgLoading] = React.useState(false);
  useEffect(() => {
    if (dispatch) {
      dispatch({
        type: 'cubeVip/fetchBordyInfo',
        payload: {
          memberId:id
        },
      })
     }
   }, []);

   /**
    * 去新增体测信息
    * @param {*} async 
    */
  const goToSave = async => {
    history.push(`/vip/center/body/save/${props.id}`);
  }

  /**
   * 取消图片预览
   */
  const handleCancel = () =>{
    setPreviewVisible(false);
  } 

  /**
   * 图片预览
   * @param {*} file 
   */
  const handlePreview = async file =>{
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }
    setPreviewImage(file.url || file.preview);
    setPreviewVisible(true);
    setPreviewTitle(file.name || file.url.substring(file.url.lastIndexOf('/') + 1))
  }

  const customRequest = (detail) => {
    setImgLoading(true)
    const formData = new FormData();
    formData.append('file',detail.file);
    upload(formData).then((result)=>{
      setImgLoading(false)
      if(result.code==0){
        fileList.push({
          uid: new Date().getTime(),
          name: 'image.png',
          status: 'done',
          url: 'http://mmm.supercube.vip/'+result.data
        });
        setFileList(fileList)
      }else{
        message.warn(result.message)
      }
    })
}


  const uploadButton = (<div><PlusOutlined /><div className="ant-upload-text">上传</div></div>);

  return (
    <GridContent>
            <Card
              title="会员体测"
              style={{
                marginBottom: 24,
              }}
              bordered={false}
            >
            <Card type="inner" title="图片数据" style={{marginBottom:24}}>
            <AuthUpload auth={[`vip:add:body`]}
                listType="picture-card"
                fileList={fileList}
                customRequest={customRequest}
              >
                { uploadButton }
              </AuthUpload>
            </Card>
            <Card type="inner" title="列表数据" extra={<Tooltip placement="top" title="新增体测数据"><AuthPlus auth={[`vip:add:body`]} onClick={()=>goToSave()}/></Tooltip>} style={{marginBottom:24}}>
              <Table
                  rowKey="id"
                  pagination={false}
                  loading={loading}
                  dataSource={bordyRecord}
                  columns={columns}
                />
            </Card>
          </Card>
          <Modal
              visible={previewVisible}
              title={previewTitle}
              footer={null}
              onCancel={handleCancel}
            >
              <img alt="example" style={{ width: '100%' }} src={previewImage} />
            </Modal>
          </GridContent>
  );
};

export default connect(({ loading,cubeVip }) => ({
  loading: loading.effects['cubeVip/fetchBordyInfo'],
  bordyRecord:cubeVip.bordyRecord
}))(Info);
